package com.hg.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.hg.cache.FIFOCache;
import com.hg.forSearch.db.dto.ForSearchDTO;
import com.hg.forSearch.service.ForSearchService;
import com.hg.timer.SystemTimerService;
import com.hg.util.action.WebHelper;
import com.hg.util.common.Common;

public class AdminsServlet extends HttpServlet
{
	 /**
     * 日志对象
     */
    private static final Logger log = LoggerFactory.getLogger(AdminsServlet.class);
	Gson gson = new Gson();
	Map<String, Object> map = new HashMap<String, Object>();
	String folder_name = "admins";
	/**
	 * Constructor of the object.
	 */
	public AdminsServlet()
	{
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy()
	{
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		String url = request.getRequestURI();	//=项目名+后面路径
		
		String contextPath = request.getContextPath();	//项目名
        if (!url.startsWith(contextPath)) contextPath = "";
        if (contextPath != null) url = url.substring(contextPath.length());		//uri=uri-项目名 	只剩下文件路径
        
		/**
		 *admins/payment/uninstall.do
		*/	
        String module="";	//模块名
        String action="";	//动作名
        String[] module_action =null;
        
		map = checkUrl(url);
		int err_code =(int) map.get("err_code");
		if(-1==err_code){
			module_action = (String[]) map.get("err_msg");
			module = module_action[0];
			action = module_action[1];
			
		}else{
			/*out.write(gson.toJson(map));
			out.flush();
			out.close();*/
			module="index";	//模块名
	        action="login";	//动作名
		}
		
		if(!("index".equals(module) && "login".equals(action))){
			if(!("index".equals(module) && "isExist".equals(action))){	//登录
				//需要验证登录
				if(!WebHelper.isLogin(request)){
					//没有登录
					module="index";	//模块名
					action="login";	//动作名
				}
			}
		}
		
		String cs = "com.hg.admin.action."+Common.UpStr(module)+"Action";	//类的路径	PaymentAction
		try{
			Class c = Class.forName(cs);
			try{
				Method m = c.getMethod(action,Map.class);
				try{
					Map map_obj = new HashMap();
					map_obj.put("request", request);
					map_obj.put("response", response);
					map_obj.put("module", module);	//模块
					map_obj.put("action", action);	//动作
					map_obj.put("folder_name", folder_name);	//文件夹的名字
					map_obj.put("tpl_url", "WEB-INF/ftl/");	//模板位置
					String project_url = Common.getProjectUrl(request);
					
					map_obj.put("project_url", project_url); //项目路径
					map_obj.put("pre_url", project_url+"/"+folder_name+"/"+module+"/"+action+".do"); //当前路径
					
					String queryStr=request.getQueryString();
					if(queryStr==null || "".equals(queryStr)){
						map_obj.put("pre_url_param",map_obj.get("pre_url")+"?qiu=1" );
					}else{
						map_obj.put("pre_url_param",map_obj.get("pre_url")+"?"+queryStr );
					}
					
					map_obj.put("cache", this.cache);	//缓存对象
					Object o=m.invoke(c.newInstance(), map_obj);
				}
				catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
						| InstantiationException e){
					e.printStackTrace();
					log.info("运行时异常:", e);
					map.put("err_code", 1013);
					map.put("err_msg", "非法访问,服务器正忙");
					out.write(gson.toJson(map));
					out.flush();
					out.close();
				}
			}
			catch (NoSuchMethodException | SecurityException e){
				map.put("err_code", 1012);
				map.put("err_msg", "非法访问,动作找不到");
				out.write(gson.toJson(map));
				out.flush();
				out.close();
			}
		}
		catch (ClassNotFoundException e){
			map.put("err_code", 1011);
			map.put("err_msg", "非法访问,模块找不到");
			out.write(gson.toJson(map));
			out.flush();
			out.close();
		}
	}
	
	/**
	 * admins/payment/uninstall.do
	 * @param url	admins/payment/uninstall.do
	 * @return
	 */
	private Map<String, Object> checkUrl(String url){
		Map<String, Object> mapP = new HashMap<String, Object>();
		if(url.endsWith(".do") && -1!=url.indexOf("/"+folder_name+"/")){
			
			String module_action_str = url.replace("/"+folder_name+"/", "").replace(".do", "");
			String[] module_action = module_action_str.split("/");
			if(2== module_action.length){
				if(module_action[0].length()>0 && module_action[1].length()>0){
					mapP.put("err_code", -1);
					mapP.put("err_msg", module_action);
					return mapP;
				}
			}
		}
		mapP.put("err_code", 1001);
		mapP.put("err_msg", "非法访问,地址格式不对");
		
		return mapP;
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		doGet(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException
	{
		// Put your code here
		this.cache=new FIFOCache<String, Object>(0, 0);	//还不知道时间的单位是多少,0表示不限大小,不限时间
		ForSearchService forS = new ForSearchService();
		
		List<ForSearchDTO> list=forS.getAll("hh_base_m_config_search");
		Map<String,String> m_config= new HashMap<String,String>();
		for(int i=0;i<list.size();i++){
			ForSearchDTO dto = list.get(i);
			m_config.put(dto.getId(), dto.getName());
		}
		
		this.cache.put("m_config", m_config);
		
		try{
			time_interval = Integer.parseInt(this.getInitParameter("time_interval").trim());
		}catch(Exception e){
			e.printStackTrace();
			time_interval=10;
		}
		
		final String remote_api_url = m_config.get("weixin_config_remote_api_url").trim();
		timer = new java.util.Timer();
		timer.schedule(new java.util.TimerTask() {
            public void run() {
            	sts.timedTask(remote_api_url);
            }
        }, new java.util.Date(), time_interval*60*1000);//90*60=1.5小时
	}
	public static FIFOCache<String, Object> cache = null;
	
	int time_interval=10;
	/**
     * 时间对象
     */
    private java.util.Timer timer = null;//will auto destroy
    SystemTimerService sts = new SystemTimerService();
}
